package cn.tedu.demo02lwd.controller;

import cn.tedu.demo02lwd.entity.Comp;
import cn.tedu.demo02lwd.mapper.CompMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/comp/")
public class CompController {

    @Autowired(required = false)
    CompMapper compMapper;

    @Value("${dirPath}")
    private String dirPath;

    @PostMapping("insert")
    public int insert(Comp comp, MultipartFile picFile) throws IOException {
        //此处没有判断是否登录
//        User user = (User) session.getAttribute("user");
//        if (user==null){//代表未登录
//            return 2;
//        }
        System.out.println("comp = " + comp + ", picFile = " + picFile);
        String fileName = picFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;

        SimpleDateFormat format = new SimpleDateFormat("/YY/MM/DD");
        String datePath = format.format(new Date());

        File dirFile = new File(dirPath+datePath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }

        File file = new File(dirPath+datePath+fileName);
        //保存上传的文件
        picFile.transferTo(file);
        //图片路径添加到comp对象里面
        comp.setUrl(datePath+fileName);
        comp.setCreated(new Date());
        compMapper.insert(comp);

        return 1;  //表示添加成功

    }

}






